package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Resource
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private DishMapper dishMapper;

    @Resource
    private DishFlavorMapper dishFlavorMapper;

    /**
     * 新增菜品和对应的口味
     * @param dishDTO
     */
    @Transactional//涉及到多表操作，需要保证数据的一致性
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        //向菜品表插入1条数据，且持久层需要返回dishId到Dish类
        dishMapper.insert(dish);
        //获取insert语句生成的主键值
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() > 0){
            //遍历并将dishId赋值
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
            //向口味表重插入n条数据，直接将集合对象传入，批量插入
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //开始分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        //下面是原始代码，但使用List<Dish>其实并不合适，因为响应的方式还是要给予DishVO来做的
        /**
         *         Page<Dish> page= dishMapper.pageQuery(dishPageQueryDTO);
         *         List<Dish> dishList = page.getResult();
         *         List<DishVO> dishVOList = new ArrayList<>();
         *         DishVO dishVO = new DishVO();
         *         dishList.forEach(dish -> {
         *             BeanUtils.copyProperties(dish, dishVO);
         *             String name = categoryMapper.queryById(dish.getCategoryId()).getName();
         *             dishVO.setCategoryName(name);
         *             dishVOList.add(dishVO);
         *         });
         *         return new PageResult(page.getTotal(), dishVOList);
         */
        //在Mapper中使用左外连接的方式连接表做查询
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.startOrStop(dish);
    }

    /**
     * 菜品批量删除，业务规则：
     *  1、可以删除一个或多个（批量删除）
     *  2、起售中的菜品不能删除
     *  3、被套餐关联的菜品不能删除
     *  4、删除菜品后，关联的口味数据也要删除
     * @param ids
     */
    @Transactional//涉及多表操作需要加事务注解
    public void deleteBatch(List<Long> ids) {
        //是否有起售中的菜品
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if(dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //是否被套餐关联了
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(setmealIds != null && setmealIds.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }


        /**
         * 下面的方式会发出太多SQL语句，对性能影响较大
         * ids.forEach(id -> {
         *      dishMapper.deleteById(id);
         *      dishFlavorMapper.deleteByDishId(id);
         * });
         */
        //删除菜品表中的菜品数据
        dishMapper.deleteByIds(ids);
        //删除菜品关联的口味数据
        dishFlavorMapper.deleteByDishIds(ids);
    }

    /**
     * 修改菜品信息
     * @param dishDTO
     */
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        dishMapper.update(dish);
        if(flavors != null && flavors.size() > 0){
            dishFlavorMapper.deleteByDishId(dish.getId());
            //如果是新增的口味数据类型，dishId会为空，需要人为赋值
            flavors.forEach(flavor -> flavor.setDishId(dish.getId()));
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 根据id查询菜品和对应的口味数据
     * @param id
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        Dish dish = dishMapper.getById(id);
        List<DishFlavor> flavors = dishFlavorMapper.getFlavorsByDishId(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);
        return dishVO;
    }
}
